package com.net.framework.help.utils;

import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;

/**
 * @ClassName: ImageTextMixingUtil.java
 * @author zhangxiaobin
 * @email 154722566@qq.com
 * @version V1.0
 * @Date 2016年3月28日 上午11:41:10
 * @Description: 图文混搭工具类
 */
public class ImageTextMixingUtil {
	private static final int LEFT = 0;// 图片在文字的左边
	private static final int RIGHT = 1;// 图片在文字的右边

	/**
	 * @param str
	 *            要显示的文字
	 * @param drawableRes
	 *            要显示的图片
	 * @param gravity
	 *            图片在文字的左边还是右边
	 * @return 图文混搭后的字符串，可直接映射到textview控件上做展示
	 */
	public static Spanned gettTextMixing(String str, int drawableRes, int gravity) {
		return Html.fromHtml(descString(str, drawableRes, gravity), getImageGetterInstance(), null);
	}

	/**
	 * 字符串
	 * 
	 * @return
	 */
	private static String descString(String str, int drawableRes, int gravity) {
		String text = null;
		if (gravity == LEFT) {
			text = "<img src='" + drawableRes + "'/>" + str;
		} else if (gravity == RIGHT) {
			text = str + "<img src='" + drawableRes + "'/>";
		}
		return text;
	}

	/**
	 * ImageGetter用于text图文混排
	 * 
	 * @return
	 */
	private static ImageGetter getImageGetterInstance() {
		ImageGetter imgGetter = new ImageGetter() {
			@Override
			public Drawable getDrawable(String source) {
				int id = Integer.parseInt(source);
				Drawable d = UIUtils.getDrawable(id);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				return d;
			}
		};
		return imgGetter;
	}

}
